document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('search-input');
    const searchButton = document.getElementById('search-button');
    const searchResults = document.getElementById('search-results');
    const errorMessage = document.getElementById('error-message');
    const playerSection = document.getElementById('player-section');
    const songTitle = document.getElementById('song-title');
    const songArtist = document.getElementById('song-artist');
    const songCover = document.getElementById('song-cover');
    const audioPlayer = document.getElementById('audio-player');
    const lyricsContainer = document.querySelector('.lyrics');
    const lyricsParent = document.querySelector('.lyrics-container');

    const playPauseButton = document.getElementById('play-pause-button');
    const prevButton = document.getElementById('prev-button');
    const nextButton = document.getElementById('next-button');

    const progressBar = document.getElementById('progress-bar');
    const currentTimeElement = document.getElementById('current-time');
    const durationElement = document.getElementById('duration');

    const sidebarToggleButton = document.getElementById('sidebar-toggle');
    const closeButton = document.getElementById('sidebar-close-button');
    const sidebarOverlay = document.getElementById('sidebar-overlay');

    let lyricsData = [];
    let currentLineIndex = -1;
    let playlist = [];
    let currentSongIndex = -1;

    // 事件监听
    searchButton.addEventListener('click', searchMusic);
    searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            searchMusic();
        }
    });

    playPauseButton.addEventListener('click', togglePlayPause);
    prevButton.addEventListener('click', playPreviousSong);
    nextButton.addEventListener('click', playNextSong);

    audioPlayer.addEventListener('ended', playNextSong);

    // 更新进度条和时间显示
    audioPlayer.addEventListener('timeupdate', updateProgress);
    audioPlayer.addEventListener('loadedmetadata', () => {
        durationElement.textContent = formatTime(audioPlayer.duration);
    });

    progressBar.addEventListener('input', seekAudio);

    // 侧边栏控制
    sidebarToggleButton.addEventListener('click', openSidebar);
    closeButton.addEventListener('click', closeSidebar);
    sidebarOverlay.addEventListener('click', closeSidebar);

    function openSidebar() {
        playerSection.classList.add('active');
        sidebarOverlay.classList.add('active');
    }

    function closeSidebar() {
        playerSection.classList.remove('active');
        sidebarOverlay.classList.remove('active');
    }

    // 定义 updateProgress 函数
    function updateProgress() {
        const currentTime = audioPlayer.currentTime;
        const duration = audioPlayer.duration;
        if (duration) {
            const progressPercent = (currentTime / duration) * 100;
            progressBar.value = progressPercent;
            currentTimeElement.textContent = formatTime(currentTime);
        }
    }

    // 定义 seekAudio 函数
    function seekAudio() {
        const duration = audioPlayer.duration;
        if (duration) {
            const seekTime = (progressBar.value / 100) * duration;
            audioPlayer.currentTime = seekTime;
        }
    }

    // 定义 formatTime 函数
    function formatTime(time) {
        const minutes = Math.floor(time / 60) || 0;
        const seconds = Math.floor(time % 60) || 0;
        return `${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
    }

    // 页面加载时展开侧边栏并显示默认文本
    openSidebar();

    async function searchMusic() {
        const searchTerm = searchInput.value.trim();
        if (!searchTerm) {
            errorMessage.textContent = '请输入搜索关键词。';
            errorMessage.style.display = 'block';
            return;
        }
        try {
            const response = await fetch(`/search?name=${encodeURIComponent(searchTerm)}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            displaySearchResults(data.songs);
            errorMessage.textContent = '';
            errorMessage.style.display = 'none';
        } catch (error) {
            console.error('Error:', error);
            errorMessage.textContent = '搜索时发生错误，请稍后再试。';
            errorMessage.style.display = 'block';
            searchResults.innerHTML = '';
        }
    }

    function displaySearchResults(songs) {
        searchResults.innerHTML = '';
        if (songs.length === 0) {
            searchResults.innerHTML = '<p>没有找到相关歌曲</p>';
            return;
        }

        // 更新播放列表
        playlist = songs;

        songs.forEach((song, index) => {
            const songElement = document.createElement('div');
            songElement.classList.add('song-item', 'fade-in');
            songElement.innerHTML = `
                <h3>${song.name}</h3>
                <p>艺术家: ${song.artist}</p>
                <p>专辑: ${song.album}</p>
                <p>平台: ${getPlatformName(song.type)}</p>
            `;
            songElement.addEventListener('click', () => playSong(song, index));
            searchResults.appendChild(songElement);
        });
    }

    function getPlatformName(type) {
        const platforms = {
            'wy': '网易云音乐',
            'qq': 'QQ音乐',
            'kw': '酷我音乐',
            'mg': '咪咕音乐'
        };
        return platforms[type] || type;
    }

    async function playSong(song, index) {
        try {
            const response = await fetch(`/play?id=${song.id}&type=${song.type}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();

            songTitle.textContent = data.name;
            songArtist.textContent = data.artist;
            songCover.src = data.pic;
            audioPlayer.src = data.url;

            // 解析歌词
            lyricsData = parseLyrics(data.lrc || '');
            displayLyrics(lyricsData);

            // 不再自动打开侧边栏
            // playerSection.classList.add('active');
            // appContainer.classList.add('sidebar-open');
            // sidebarOverlay.style.display = 'block';

            audioPlayer.play();
            errorMessage.style.display = 'none';

            // 更新当前播放索引
            currentSongIndex = index;

            // 重置歌词状态
            currentLineIndex = -1;
            audioPlayer.removeEventListener('timeupdate', updateLyrics);
            audioPlayer.addEventListener('timeupdate', updateLyrics);

            // 更新播放/暂停按钮图标
            playPauseButton.innerHTML = '<i class="fas fa-pause"></i>';

        } catch (error) {
            console.error('Error:', error);
            errorMessage.textContent = '播放歌曲时发生错误，请稍后再试。';
            errorMessage.style.display = 'block';
        }
    }

    function togglePlayPause() {
        if (audioPlayer.paused) {
            audioPlayer.play();
            playPauseButton.innerHTML = '<i class="fas fa-pause"></i>';
        } else {
            audioPlayer.pause();
            playPauseButton.innerHTML = '<i class="fas fa-play"></i>';
        }
    }

    function playPreviousSong() {
        if (currentSongIndex > 0) {
            const previousSong = playlist[currentSongIndex - 1];
            playSong(previousSong, currentSongIndex - 1);
        } else {
            console.log('已经是第一首歌');
        }
    }

    function playNextSong() {
        if (currentSongIndex < playlist.length - 1) {
            const nextSong = playlist[currentSongIndex + 1];
            playSong(nextSong, currentSongIndex + 1);
        } else {
            console.log('已经是最后一首歌');
        }
    }

    function parseLyrics(lrc) {
        const lines = lrc.split('\n');
        const result = [];
        const timePattern = /\[(\d{1,2}):(\d{1,2})(\.\d{1,3})?\]/g;
        for (const line of lines) {
            let matches;
            let times = [];
            while ((matches = timePattern.exec(line)) !== null) {
                const minutes = parseInt(matches[1]);
                const seconds = parseInt(matches[2]);
                const milliseconds = parseFloat(matches[3] || 0);
                const time = minutes * 60 + seconds + milliseconds;
                times.push(time);
            }
            const text = line.replace(timePattern, '').trim();
            for (const time of times) {
                result.push({time, text: text || '♪'});
            }
        }
        result.sort((a, b) => a.time - b.time);
        return result;
    }

    function displayLyrics(lyricsArray) {
        lyricsContainer.innerHTML = '';
        lyricsArray.forEach((line, index) => {
            const p = document.createElement('p');
            p.textContent = line.text;
            p.id = 'line-' + index;
            lyricsContainer.appendChild(p);
        });
    }

    // 更新歌词
    function updateLyrics() {
        if (!lyricsData.length) return;
        const currentTime = audioPlayer.currentTime;
        const index = getCurrentLineIndex(currentTime);
        if (index !== currentLineIndex) {
            updateLyricsHighlight(index);
        }
    }

    function getCurrentLineIndex(currentTime) {
        let low = 0;
        let high = lyricsData.length - 1;
        while (low <= high) {
            const mid = Math.floor((low + high) / 2);
            if (lyricsData[mid].time <= currentTime && (mid === lyricsData.length - 1 || lyricsData[mid + 1].time > currentTime)) {
                return mid;
            } else if (lyricsData[mid].time > currentTime) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }

    function updateLyricsHighlight(index) {
        if (index === currentLineIndex) return;
        const previousLine = document.getElementById('line-' + currentLineIndex);
        if (previousLine) previousLine.classList.remove('current-line');

        currentLineIndex = index;
        const currentLine = document.getElementById('line-' + currentLineIndex);
        if (currentLine) {
            currentLine.classList.add('current-line');
            scrollToCurrentLine();
        }
    }

    function scrollToCurrentLine() {
        if (!lyricsData.length) return;
        const currentLine = document.getElementById('line-' + currentLineIndex);
        if (currentLine) {
            const lineHeight = currentLine.offsetHeight;
            const containerHeight = lyricsParent.offsetHeight;
            const offset = (currentLine.offsetTop + lineHeight / 2) - containerHeight / 2;
            lyricsContainer.style.transform = `translateY(-${offset}px)`;
        }
    }

});
